package com.etime.servlet;

import com.etime.entity.Student;
import com.etime.service.impl.StudentEnrollServiceImpl;
import com.etime.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
@WebServlet("/studentServlet")
@MultipartConfig
public class StudentServlet extends BaseServlet {
  StudentServiceImpl studentService = new StudentServiceImpl();
  protected void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    int id = Integer.parseInt(req.getParameter("id"));
    studentService.delete(id);
    resp.sendRedirect("showServlet");
  }
  protected void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String password = req.getParameter("password");
    String sid = req.getParameter("sid");
    studentService.update(password, Integer.parseInt(sid));
    resp.sendRedirect("showServlet");
  }
  protected void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    String name = req.getParameter("name");
    String password = req.getParameter("password");
    Part part = req.getPart("photo");
    String path = "D://photo";
    File file = new File(path);
    if (!file.exists()){
      file.mkdirs();
    }
    String photoName = part.getSubmittedFileName();
    part.write(path+"/"+photoName);
    Student student = new Student(name, password, photoName);
    boolean value = studentService.insert(student);
    resp.sendRedirect("showServlet");
  }
  protected void enroll(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    StudentEnrollServiceImpl studentEnrollService = new StudentEnrollServiceImpl();
    boolean value = studentEnrollService.enroll(req.getParameter("username"), req.getParameter("psw"));
    if (value){
      resp.sendRedirect("login.html");
    }
    else {
      resp.sendRedirect("enroll.html");
    }
  }

  protected void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    boolean login = studentService.login(req.getParameter("username"), req.getParameter("psw"));
    if (login){
      resp.sendRedirect("index.html");
    }
    else {
      resp.sendRedirect("login.html");
    }
  }
}
